package com.alwvfhp.tools.Powershell.service;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alwvfhp.tools.Powershell.ResultCode;
import com.alwvfhp.tools.Powershell.interf.PResult;
import com.alwvfhp.tools.Powershell.interf.SPowershell;
import com.alwvfhp.tools.Powershell.thread.ClearMapThread;
import com.alwvfhp.tools.Powershell.thread.ManagerThread;
import com.alwvfhp.tools.Powershell.thread.PowerShellThread;
import com.alwvfhp.tools.Powershell.util.FileUtil;
/**
 *<title>FlowService<title>
 *<pre>
 *组装powershell命令，进行命令运行前准备
 *</pre>
 *Author : sujian
 *Date   : 2014年8月12日
 */
public class QidianPowershell implements SPowershell{
	/**
	 * 保存运行powershell命令的状态
	 */
	private final static Map<String,QidianPowershell.Result> mapThread;
	static{
		mapThread=new HashMap<String,QidianPowershell.Result>();
	}
	public class Result implements PResult{
		public ResultCode rCode=ResultCode.RUNNING;
		List<String> rList=new LinkedList<String>();
		List<String> eList=new LinkedList<String>();
		public void add(String res) {
			rList.add(res);
		}
		public List<String> getResult() {
			return rList;
		}
		public ResultCode getRCode(){
			return this.rCode;
		}
		public void setRCode(ResultCode rc){
			this.rCode=rc;
		}
		@Override
		public void adderror(String err) {
			
		}
		@Override
		public List<String> getError() {
			
			return null;
		}
	}
	/**
	 *TODO 把命令写入文件，等待运行
	 *@param order 传入的命令
	 *@return String 获取结果的唯一标识符
	 *@throws Exception
	 */
	public String sendOrder(String...order) throws Exception{
		String newFile=UUID.randomUUID().toString();
		List<String> oList=new LinkedList<String>();
		for(String one:order){
			oList.add(one);
		}
		oList.add("echo OK");
		new FileUtil().writeData(new File(newFile+".ps1"),"utf-8",oList.toArray());
		return exec(newFile);
	}
//	public String sendOrder(File fileName) throws Exception{
//		if(!fileName.getName().endsWith("\\.ps1"))return null;
//		String newFile=UUID.randomUUID().toString();
//		Result re = new Result();
//		mapThread.put(newFile, re);
////		new PowerShellThread<Result>(re,);//开启新线程运行
//		return newFile;
//	}

	public QidianPowershell.Result getResult(String flags) {
		Result re= mapThread.get(flags);
		if(re.rCode.equals(ResultCode.OK))mapThread.remove(flags);
		return mapThread.get(flags);
	}
	/**
	 *TODO 
	 *@param newFile
	 *@return 
	 */
	private String exec(String newFile){
		Result re = new Result();
		mapThread.put(newFile, re);
		Thread thread=new Thread(new PowerShellThread<Result>(re,new File(newFile).getAbsolutePath()));//开启新线程运行
		thread.start();
		new Thread(new ManagerThread(thread,60000)).start();//一分钟未完成，强制关闭
		new Thread(new ClearMapThread(re,55000));
		return newFile;
	}
	@Override
	public String sendOrder(String IP, String user, String pass,
			String... order) throws Exception {
		List<String> oList=new LinkedList<String>();
		oList.add("$IP='"+IP+"'");
		oList.add("$user='"+user+"'");
		oList.add("$userpass='"+pass+"'");
		oList.add("$pass=convertto-securestring $userpass -asplaintext -force");
		oList.add("$cred = New-Object System.Management.Automation.PsCredential $user, $pass");
		oList.add("$s = New-PSSession -ComputerName $IP -Credential $cred");
		StringBuffer buf = new StringBuffer();
		boolean flag=true;
		for(String str:order){
			if(flag)flag=false;
			else buf.append(";");
			buf.append(str);
		}
		oList.add("Invoke-Command -Session $s -ScriptBlock { "+new String(buf)+" }");
		final int size=oList.size();
		return sendOrder((String[])oList.toArray(new String[size]));
	}
}
